/* 房间生态拓展 负责房间的爬虫生产/布局/状态检测/建筑记忆更新 */
import {modifySpawnData} from '@/prototype/room/core/constant'
import { adaption_body, CalculateEnergy, colorful, GenerateAbility, getDistance, isInArray } from '@/utils'
import { BluePrintA } from './blueprint'
import { build_, harvest_, upgrade_ } from './fun'
export default class RoomEcoshpereExtension extends Room {
    /* 爬虫数据挂载 */
    public MountSpawnData():void{
        /* 全局孵化数据初始化 */
        if (!global.CreepNumData) global.CreepNumData = {}
        if (!global.CreepNumData[this.name]) global.CreepNumData[this.name] = {}
        global.CreepNumData[this.name] = {
            /* 基本功能爬虫 */
            "harvest":{num:1,ability:GenerateAbility(1,1,2),adaption:true,level:5,fun:harvest_},
            "upgrade":{num:1,ability:GenerateAbility(1,1,2),adaption:true,fun:upgrade_},
            "build":{num:0,ability:GenerateAbility(2,2,3),adaption:true,fun:build_},
            /* 任务型爬虫 */
            /* 中央搬运工 */
            "manage":{num:0,ability:GenerateAbility(0,2,2),must:true,adaption:true,level:3},
            "transport":{num:0,ability:GenerateAbility(0,2,2),adaption:true,must:true,level:2},
            /* 房间维护工 */
            "repair":{num:0,ability:GenerateAbility(1,1,2),must:true},
            /* 冲级工 */
            'level':{num:0,ability:GenerateAbility(20,4,10)},
            /* 斥候 */
            'scout':{num:0,ability:GenerateAbility(0,0,1)},
            /* 占领者 */
            'claim':{num:0,ability:GenerateAbility(0,0,1,0,0,0,1,0)},
            /* boosted援建一体机 */
            'architect':{num:0,ability:GenerateAbility(15,20,10,0,0,2,0,3)},
            /* 协助升级 */
            'upgrade-help':{num:0,ability:GenerateAbility(15,20,10,0,0,5)},
            'rear-help':{num:0,ability:GenerateAbility(3,32,10,0,0,3,0,2)},
            /* 攻防一体机 */
            'aio':{num:0,ability:GenerateAbility(0,0,10,0,5,23,0,12)},
            /* 矿物采集者 */
            'mineral':{num:0,ability:GenerateAbility(15,15,15)},
            /* power采集相关 */
            'power-attack':{num:0,ability:GenerateAbility(0,0,20,20)},
            'power-heal':{num:0,ability:GenerateAbility(0,0,25,0,0,25)},
            'power-carry':{num:0,ability:GenerateAbility(0,32,16)},
            /* deposit采集相关 */
            'deposit':{num:0,ability:GenerateAbility(15,10,25)},
            /* 四人小队 R类型-前排*/
            'X-R-A':{num:0,ability:GenerateAbility(0,0,10,0,26,2,0,12),mem:{creepType:'attack'}},
            'X-R-B':{num:0,ability:GenerateAbility(0,0,10,0,2,26,0,12),mem:{creepType:'heal'}},
            /* 四人小队 A类型 */
            'X-A-A':{num:0,ability:GenerateAbility(0,0,10,28,0,0,0,12),mem:{creepType:'attack'}},
            'X-A-B':{num:0,ability:GenerateAbility(0,0,10,0,2,26,0,12),mem:{creepType:'heal'}},
            /* 双人小队 */
            'double-attack':{num:0,ability:GenerateAbility(0,0,10,28,0,0,0,12)},
            'double-dismantle':{num:0,ability:GenerateAbility(28,0,10,0,0,0,0,12)},
            'double-heal':{num:0,ability:GenerateAbility(0,0,10,0,0,28,0,12)},
            /* 外矿 */
            'out-claim':{num:0,ability:GenerateAbility(0,0,2,0,0,0,2,0)},
            'out-harvest':{num:0,ability:GenerateAbility(4,2,4,0,0,0,0,0)},
            'out-car':{num:0,ability:GenerateAbility(1,5,6,0,0,0,0,0)},
            'out-defend':{num:0,ability:GenerateAbility(0,0,5,5,0,5,0,0)},
            /* 主动防御 */
            'defend-attack':{num:0,ability:GenerateAbility(0,0,10,40,0,0,0,0),must:true},
            'defend-range':{num:0,ability:GenerateAbility(0,0,10,0,40,0,0,0)},
            /* 大黄 */
            'dismantle':{num:0,ability:GenerateAbility(40,0,10,0,0,0,0,0)},
            /* 小紫 */
            'claim-attack':{num:0,ability:GenerateAbility(0,0,15,0,0,0,15,0)},
            'om-killer':{num:0,ability:GenerateAbility(1,0,2,0,0,0,0,0)},
        }
    }
    /* 爬虫数据二次加工 */
    public ModifySpawnData():void{
        var GlobalData = global.CreepNumData[this.name]
        if (!GlobalData) return
        var level = this.controller.level
        for (var roleKey of Object.keys(modifySpawnData))
        {
            if (!GlobalData[roleKey]){continue}
            var bodyArray = modifySpawnData[roleKey][level].bodypart
            GlobalData[roleKey].ability = GenerateAbility(bodyArray[0],bodyArray[1],bodyArray[2],bodyArray[3],bodyArray[4],bodyArray[5],bodyArray[6],bodyArray[7])
            GlobalData[roleKey].num = modifySpawnData[roleKey][level].num
        }
    }
    /* 房间状态识别、操作 */
    public RoomState():void{
        // 每5tick观察一次房间状态，如果发现敌人，房间状态变为war，否则为peace
        if (Game.time % 5 == 0)
        {
            // 安全模式下和平模式
            if (this.controller.safeMode)
            {
                this.memory.roomSTATE = 'peace'
                return
            }
            if (!Memory.whitesheets) Memory.whitesheets = []
            var enemy = this.find(FIND_HOSTILE_CREEPS,{filter:(creep)=>{
                return !isInArray(Memory.whitesheets,creep.owner.username)
            }})
            var enemyPowerCreep = this.find(FIND_HOSTILE_POWER_CREEPS,{filter:(creep)=>{
                return !isInArray(Memory.whitesheets,creep.owner.username)
            }})
            if (enemy[0] || enemyPowerCreep[0]) this.memory.roomSTATE = 'war'
            else this.memory.roomSTATE = 'peace'
        }
        /* 战争状态下，非必须爬虫都不允许生产 */
        if (this.memory.roomSTATE == 'war')
        {
            for (var i of Object.keys(global.CreepNumData[this.name]))
            {
                if (!global.CreepNumData[this.name][i].must) global.CreepNumData[this.name][i].num = 0
            }
            
        }
    }
    /* 爬虫自适应生产 监测全局列表中的爬虫状态 */
    public CreepSpawn():void{
        var GlobalData = global.CreepNumData[this.name]
        if (!GlobalData) return
        /* 房间能量上限和房间目前所拥有能量 */
        const allEnergyCapacity = this.energyCapacityAvailable
        const allEnergy = this.energyAvailable
        let spawnRole:SpawnRoleData = {}
        for (var sample of Object.keys(GlobalData))
        {
            /* 孵化优先等级默认为10 */
            if (!GlobalData[sample].level) GlobalData[sample].level = 10
            const actual_num = _.filter(Game.creeps,(creep) => creep.memory.role == sample && creep.memory.belong == this.name).length
            if (actual_num < GlobalData[sample].num)
            {
                /* 如果房间能量上限低于爬虫生产所需能量，则启动自适应生产 */
                if(allEnergyCapacity < CalculateEnergy(GlobalData[sample].ability))
                    adaption_body(GlobalData[sample].ability,allEnergyCapacity)
                /* 如果爬虫是adaption 且满足相关情况，则启动自适应生产 */
                if (allEnergy < CalculateEnergy(GlobalData[sample].ability) && actual_num==0 && GlobalData[sample].adaption)
                {
                    adaption_body(GlobalData[sample].ability,allEnergy)
                    
                }
                /* 根据孵化优先等级排序 */
                if (Object.keys(spawnRole).length == 0)
                {
                    spawnRole = {role:sample,level:GlobalData[sample].level}
                }
                else
                {
                    if (GlobalData[sample].level < spawnRole.level)
                    {
                        spawnRole.role = sample
                        spawnRole.level = GlobalData[sample].level
                    }
                }
            }
        }
        if (Object.keys(spawnRole).length == 0) return
        /* 开始孵化流程 寻找当前房间所有可用的spawn */
        if (!this.memory.StructureIdData || !this.memory.StructureIdData.spawn)
        {
            if(Game.time % 10 == 0) console.log("未发现StructureIdData相关记忆！无spawn相关记忆！")
            return
        }
        for (var spawn_id of this.memory.StructureIdData.spawn)
        {
            var thisSpawn = Game.getObjectById(spawn_id) as StructureSpawn
            /* 如果没发现记忆中的spawn，说明记忆过期，需要更新记忆 */
            if (!thisSpawn) 
            {
                var index = this.memory.StructureIdData.spawn.indexOf(spawn_id)
                this.memory.StructureIdData.spawn.splice(index,1)
                continue
            }
            if (thisSpawn.spawning) continue
            thisSpawn.hatchCreep(spawnRole.role,GlobalData[spawnRole.role].ability,GlobalData[spawnRole.role].mem)

            return
        }
    }
    /* 建筑记忆更新 */
    public UpdateStructureId():void{
        if (!this.memory.StructureIdData) this.memory.StructureIdData = {}
        var level = this.controller.level
        /* 存在全局中的每个房间的时间参数 */
        if (!global.Gtime) global.Gtime = {}
        if (!global.Gtime[this.name]) global.Gtime[this.name] = Game.time
        /* 虫卵识别 */
        if (!this.memory.StructureIdData.spawn || this.memory.StructureIdData.spawn.length < 3)
        {
            if (!this.memory.StructureIdData.spawn) this.memory.StructureIdData.spawn = []
            /* 根据等级 */
            if (level <= 6 && this.memory.StructureIdData.spawn.length < 1)
            {
                    var ASpawn = this.getStructure(STRUCTURE_SPAWN) as StructureSpawn[]
                    let spawns:string[] = []
                    for (var sp of ASpawn)
                    {
                        spawns.push(sp.id)  
                    }
                    this.memory.StructureIdData.spawn = spawns
            }
            if (level == 7 && this.memory.StructureIdData.spawn.length < 2)
            {
                    var ASpawn = this.getStructure(STRUCTURE_SPAWN) as StructureSpawn[]
                    let spawns:string[] = []
                    for (var sp of ASpawn)
                    {
                        spawns.push(sp.id)  
                    }
                    this.memory.StructureIdData.spawn = spawns
            }
            if (level > 7 && this.memory.StructureIdData.spawn.length < 3)
            {
                var ASpawn = this.getStructure(STRUCTURE_SPAWN) as StructureSpawn[]
                let spawns:string[] = []
                for (var sp of ASpawn)
                {
                    spawns.push(sp.id)  
                }
                this.memory.StructureIdData.spawn = spawns
            }
        }
        /* 中心点识别 */
        if (!this.memory.center_x || !this.memory.center_y)
        {
            if (this.memory.StructureIdData.spawn && this.memory.StructureIdData.spawn.length == 1)
            {
                var thisSpawn = Game.getObjectById(this.memory.StructureIdData.spawn[0]) as StructureSpawn
                if (thisSpawn)
                {
                    this.memory.center_x = thisSpawn.pos.x
                    this.memory.center_y = thisSpawn.pos.y
                }
            }
        }
        /* 近矿点和远矿点的识别 */
        if (!this.memory.StructureIdData.source1ID || !this.memory.StructureIdData.source2ID)
        {
            var allSource = this.find(FIND_SOURCES)
            var farSource:Source
            if (allSource.length < 1) return
            else if (allSource.length == 1) farSource = allSource[0]
            else
            {
                farSource = allSource[0]
                for (var s of allSource)
                {
                    if (getDistance(s.pos,this.controller.pos) > getDistance(farSource.pos,this.controller.pos))
                    {
                        farSource = s
                    }
                }
            }
            // source1是远矿点
            this.memory.StructureIdData.source1ID = farSource.id
            // source2是近矿点
            if (allSource.length == 1) this.memory.StructureIdData.source2ID = farSource.id
            else
            {
                for (var ss of allSource)
                {
                    if (ss.id != this.memory.StructureIdData.source1ID)
                        this.memory.StructureIdData.source2ID = ss.id
                }
            }
        }
        /* 资源矿识别 */
        if (!this.memory.StructureIdData.mineralID )
        {
            var Mineral_ = this.find(FIND_MINERALS)
            if (Mineral_.length == 1) this.memory.StructureIdData.mineralID = Mineral_[0].id
        }
        /* 仓库识别 */
        if (level >= 4 && !this.memory.StructureIdData.storageID)
        {
            var new_storage = this.find(FIND_MY_STRUCTURES,{filter:{structureType:STRUCTURE_STORAGE }})
            if (new_storage.length == 1) this.memory.StructureIdData.storageID = new_storage[0].id
        }
        /* 近塔识别 */
        if (!this.memory.StructureIdData.NtowerID && this.controller.level >= 3)
        {
            if (!this.memory.center_x) return
            var center = new RoomPosition(this.memory.center_x,this.memory.center_y,this.name)
            var NTower = center.getClosestStructure([STRUCTURE_TOWER],0)
            if (NTower)
            if (getDistance(NTower.pos,center) < 7) this.memory.StructureIdData.NtowerID = NTower.id
        }
        /* 远塔识别 */
        if (Game.time % 150 == 0 && this.controller.level >= 5)
        {
            if (!this.memory.StructureIdData.OtowerID) this.memory.StructureIdData.OtowerID = []
            this.memory.StructureIdData.OtowerID as string[]
            var ATowers = this.getStructure(STRUCTURE_TOWER) as StructureTower[]
            if (ATowers.length > this.memory.StructureIdData.OtowerID.length + 1)
            {
                for (var t of ATowers) 
                if (this.memory.StructureIdData.NtowerID && t.my && t.id != this.memory.StructureIdData.NtowerID && !isInArray(this.memory.StructureIdData.OtowerID as string[],t.id))
                {
                    var OtowerID = this.memory.StructureIdData.OtowerID as string[]
                    OtowerID.push(t.id)
                }
            }
        }
        /* 终端识别 */
        if (!this.memory.StructureIdData.terminalID && level >= 6)
        {
            var Terminal = this.getStructure(STRUCTURE_TERMINAL)
            if (Terminal.length == 1) this.memory.StructureIdData.terminalID = Terminal[0].id
        }
        /* 提取器识别 */
        if (!this.memory.StructureIdData.extractID && this.controller.level >= 5)
        {
            var extract = this.getStructure(STRUCTURE_EXTRACTOR)
            if (extract.length == 1) this.memory.StructureIdData.extractID = extract[0].id
        }
        /* 中央Link识别 */
        if (!this.memory.StructureIdData.center_link && this.controller.level >= 5)
        {
            if (!this.memory.center_x) return
            var position_ = new RoomPosition(this.memory.center_x,this.memory.center_y,this.name)
            var center_link = position_.getRangedStructure([STRUCTURE_LINK],3,0) as StructureLink[]
            if (center_link.length >= 1)
            this.memory.StructureIdData.center_link = center_link[0].id
        }
        /* 矿点Links识别 */
        if (!this.memory.StructureIdData.source_link && this.controller.level >= 5)
        {
            if (!this.memory.StructureIdData.source1ID) return
            var source1 = Game.getObjectById(this.memory.StructureIdData.source1ID as string) as StructureLink
            if (!source1)
            {
                delete this.memory.StructureIdData.source1ID
                return
            }
            var source_link = source1.pos.getRangedStructure([STRUCTURE_LINK],2,0) as StructureLink[]
            if (source_link.length >= 1)
            this.memory.StructureIdData.source_link = source_link[0].id
        }
        if (!this.memory.StructureIdData.source2_link && this.controller.level >= 6 && Game.time % 80 == 0)
        {
            if (!this.memory.StructureIdData.source2ID) return
            var source2 =  Game.getObjectById(this.memory.StructureIdData.source2ID as string) as StructureLink
            if (!source2)
            {
                delete this.memory.StructureIdData.source2ID
                return
            }
            var source2_link = source2.pos.getRangedStructure([STRUCTURE_LINK],2,0) as StructureLink[]
            if (source2_link.length >= 1)
            for (var sl of source2_link)
            {
                if (sl.id != this.memory.StructureIdData.source_link && sl.id != this.memory.StructureIdData.upgrade_link)
                {
                    this.memory.StructureIdData.source2_link = sl.id
                    break
                }
            }
        }
        /* 升级Link识别 */
        if (!this.memory.StructureIdData.upgrade_link && this.controller.level >= 6 && Game.time % 80 == 0)
        {
            var upgrade_link = this.controller.pos.getRangedStructure([STRUCTURE_LINK],4,0) as StructureLink[]
            if (upgrade_link.length >= 1)
            for (var ul of upgrade_link)
            {
                if (ul.id != this.memory.StructureIdData.source_link && ul.id != this.memory.StructureIdData.source2_link)
                {
                    this.memory.StructureIdData.upgrade_link = ul.id
                    break
                }
            }
        }
        /* 实验室识别 */
        if (Game.time % 200 == 0)
        {
            var ALabs = this.getStructure(STRUCTURE_LAB) as StructureLab[]
            if (ALabs.length > 1)
            {
                if (!this.memory.StructureIdData.labs) this.memory.StructureIdData.labs = []
                for (var llab of ALabs)
                {
                    if (llab.my && !isInArray(this.memory.StructureIdData.labs as string[],llab.id))
                    {
                        var labs = this.memory.StructureIdData.labs as string[]
                        labs.push(llab.id)
                    }
                }
            }
            /* 实验室合成数据 需要手动挂载，如果没有实验室合成数据，无法执行合成任务 */
            /* 里面包含自动合成相关的原料lab和产出lab数据 */
            if (!this.memory.StructureIdData.labInspect)
            {
                this.memory.StructureIdData.labInspect = {}
            }
            
        }
        /* 观察器识别 */
        if (!this.memory.StructureIdData.ObserverID && this.controller.level >= 8 )
        {
            var observer_ = this.getStructure(STRUCTURE_OBSERVER)
            if (observer_.length > 0)
            {
                this.memory.StructureIdData.ObserverID = observer_[0].id
            }
        }
        /* PowerSpawn识别 */
        if (!this.memory.StructureIdData.PowerSpawnID && this.controller.level >= 8)
        {
            var powerSpawn = this.getStructure(STRUCTURE_POWER_SPAWN)
            if (powerSpawn.length > 0)
            this.memory.StructureIdData.PowerSpawnID = powerSpawn[0].id
        }
        /* 核弹识别 */
        if (!this.memory.StructureIdData.NukerID && this.controller.level >= 8 )
        {
            var nuke_ = this.getStructure(STRUCTURE_NUKER)
            if (nuke_.length > 0)
            {
                this.memory.StructureIdData.NukerID = nuke_[0].id
            }
        }
        /* 工厂识别 */
        if (!this.memory.StructureIdData.FactoryId && this.controller.level >= 8)
        {
            var factory_ = this.getStructure(STRUCTURE_FACTORY)
            if (factory_.length > 0)
            {
                this.memory.StructureIdData.FactoryId = factory_[0].id
            }
        }
        /* 已经占用的实验室初始化 */
        if(!this.memory.RoomLabBind) this.memory.RoomLabBind = {}


    }
    /* 自动布局 */
    public AutoArrange():void{
        if (Game.shard.name == 'shard3')
        {
            if (Game.time % 25) return
        }
        else
        {
            if (Game.time % 5) return
        }
        /* 没有中心点的房间不进行自动布局 */
        if (!this.memory.center_x || !this.memory.center_y) return
        if (!this.memory.AutoArrangeLevel) this.memory.AutoArrangeLevel = 0
        const level = this.controller.level
        /* 自动布局相关 包含Link 总体建筑布局 */
        if (level > this.memory.AutoArrangeLevel)
        {
            /* 根据frameMemory里的记忆决定不同的布局 */
            if (!Memory.ControlPlan[this.name].layoutPlan)
                Memory.ControlPlan[this.name].layoutPlan = 'none'
            if (Memory.ControlPlan[this.name].layoutPlan == 'A')
            {
                this.BuildBluePrint(level,BluePrintA)
            }
            /* link/container自动规划 */
            if (level == 5)
            {
                var source1 = Game.getObjectById(this.memory.StructureIdData.source1ID) as Source
                var points = source1.pos.getSourceLinkVoid()
                if (points.length <= 0) return
                LoopA:
                for (var i of points)
                {
                    if(i.lookFor(LOOK_CONSTRUCTION_SITES).length <= 0 && i.lookFor(LOOK_STRUCTURES).length <= 0)
                    {
                        i.createConstructionSite(STRUCTURE_LINK)
                        break LoopA
                    }
                }
            }
            if (level == 6)
            {
                var controller = this.controller
                var points = controller.pos.getSourceLinkVoid()
                if (points.length <= 0) return
                LoopA:
                for (var i of points)
                {
                    if(i.lookFor(LOOK_CONSTRUCTION_SITES).length <= 0 && i.lookFor(LOOK_STRUCTURES).length <= 0)
                    {
                        i.createConstructionSite(STRUCTURE_LINK)
                        break LoopA
                    }
                }
            }
            if (level == 7)
            {
                var source2 = Game.getObjectById(this.memory.StructureIdData.source2ID) as Source
                var points = source2.pos.getSourceLinkVoid()
                if (points.length <= 0) return
                LoopA:
                for (var i of points)
                {
                    if(i.lookFor(LOOK_CONSTRUCTION_SITES).length <= 0 && i.lookFor(LOOK_STRUCTURES).length <= 0)
                    {
                        i.createConstructionSite(STRUCTURE_LINK)
                        break LoopA
                    }
                }
            }
            this.memory.AutoArrangeLevel = level
            console.log(colorful(`房间${this.name}实施建筑规划!`,'yellow'))
        }
        /* 自动重建 */
        if (!this.memory.roomSTATE) return
        if (this.memory.roomSTATE == 'peace')
        {
            /* 仅仅在和平情况下才会打开自动重建 */
            // 寻找所有属于我的建筑的数量 -1是去除controller 包含所有非控制器的我方建筑、我方建筑工地、该房间内的道路，container
            let currentNum = this.find(FIND_MY_STRUCTURES).length + this.find(FIND_MY_CONSTRUCTION_SITES).length + this.find(FIND_STRUCTURES,{filter:(structure)=>{return structure.structureType == STRUCTURE_CONTAINER || structure.structureType == STRUCTURE_ROAD}}).length - 1
            if(!this.memory.structureNum) this.memory.structureNum = 0
            this.memory.structureNum = this.getDistributionNum()
            if (currentNum > this.memory.structureNum)
            {
                console.log(currentNum)
                console.log(this.memory.structureNum)
                this.addStructureMemory()
                console.log(`房间${this.name} 更新distribution记忆!`)
            }
            else if (currentNum === this.memory.structureNum)
            {
                return
            }
            else
            {
                console.log(this.name,"检测出缺损")
                /* 运行修补函数 */
                this.repatchDistribution()
            }
        }
        else if (this.memory.roomSTATE == 'war')
        {
            /* 战争状态 */
            // 仅检测城墙、spawn、仓库、终端、实验室的数量，检测到缺损就自动开启安全模式
            let currentNum = this.find(FIND_MY_STRUCTURES,{filter:(structure)=>{
                return isInArray(['rampart','spawn','storage','terminal','lab','extension'],structure.structureType)
            }}).length
            currentNum += this.find(FIND_MY_CONSTRUCTION_SITES,{filter:(cons)=>{
                return isInArray(['rampart','spawn','storage','terminal','lab','extension'],cons.structureType)
            }}).length
            let memoryNum = 0
            console.log('currentNum:',currentNum)
            for (var index in this.memory.distribution)
            {
                if (isInArray(['rampart','spawn','storage','terminal','lab','extension'],index))
                {
                    memoryNum += this.memory.distribution[index].length
                }
            }
            console.log("memoryNum:",memoryNum)
            if (currentNum < memoryNum)
            {
                /* 说明出问题了 */
                this.controller.activateSafeMode()
            }
        }
    }

    /* 规律布局 */
    public BuildBluePrint(level:number,map:planData[]):void{
        for (var index of map)
        {
            if (level >= index.enableLevel)
            {
                let center_point:RoomPosition
                // 获取中心点
                center_point = new RoomPosition(this.memory.center_x,this.memory.center_y,this.name)
                let new_point = new RoomPosition(center_point.x + index.posX,center_point.y+index.posY,this.name)
                // 获取new_point上的建筑
                let new_point_structures = new_point.lookFor(LOOK_STRUCTURES)
                let pd:boolean = true
                if (new_point_structures.length > 0)
                for (var j of new_point_structures)
                {
                    if (j.structureType != STRUCTURE_RAMPART)
                    pd = false
                }

                if (new_point && new_point.lookFor(LOOK_CONSTRUCTION_SITES).length == 0 && pd)
                {
                    if (new_point.createConstructionSite(index.posType) != 0)
                    {
                    // console.log("创建失败:" + index.posType + '，位置为：x->'+new_point.x + ',y->'+new_point.y)
                    }
                    else
                    {
                        console.log("创建成功:" + index.posType + '，位置为：x->'+new_point.x + ',y->'+new_point.y)
                    }
                }
                else
                {
                        // console.log("位置 x=",new_point.x,',y=',new_point.y,'已经有建筑或者结构了！')
                }
            }
            /* 防止遍历无关建筑 */
            else
                return
        }
    }

    /* 获取全局建筑对象变量 由于该对象每tick都不一样，所以需要每tick都获取 */
    public GlobalStructure():void{
        // 目前只支持 storage terminal factory powerspawn 
        if (!global.Stru) global.Stru = {}
        if (!global.Stru[this.name]) global.Stru[this.name] = {}

        if (this.memory.StructureIdData.storageID)
        {
            global.Stru[this.name]['storage'] = Game.getObjectById(this.memory.StructureIdData.storageID) as StructureStorage
            if (!global.Stru[this.name]['storage'])
            {
                delete this.memory.StructureIdData.storageID
            }
        }
        if(this.memory.StructureIdData.terminalID)
        {
            global.Stru[this.name]['terminal'] = Game.getObjectById(this.memory.StructureIdData.terminalID) as StructureTerminal
            if (!global.Stru[this.name]['terminal'])
            {
                delete this.memory.StructureIdData.terminalID
            }
        }
        if (this.memory.StructureIdData.PowerSpawnID)
        {
            global.Stru[this.name]['powerspawn'] = Game.getObjectById(this.memory.StructureIdData.PowerSpawnID) as StructurePowerSpawn
            if (!global.Stru[this.name]['powerspawn'])
            {
                delete this.memory.StructureIdData.PowerSpawnID
            }
        }
        if (this.memory.StructureIdData.FactoryId)
        {
            global.Stru[this.name]['factory'] = Game.getObjectById(this.memory.StructureIdData.FactoryId) as StructureFactory
            if (!global.Stru[this.name]['factory'])
            {
                delete this.memory.StructureIdData.FactoryId
            }
        }
        if (this.memory.StructureIdData.NtowerID)
        {
            global.Stru[this.name]['Ntower'] = Game.getObjectById(this.memory.StructureIdData.NtowerID) as StructureTower
            if (!global.Stru[this.name]['Ntower'])
            {
                delete this.memory.StructureIdData.NtowerID
            }
        }
        if (this.memory.StructureIdData.OtowerID && this.memory.StructureIdData.OtowerID.length > 0)
        {
            var otlist = global.Stru[this.name]['Atower'] = [] as StructureTower[]
            for (var ti of this.memory.StructureIdData.OtowerID)
            {
                var ot = Game.getObjectById(ti) as StructureTower
                if (!ot)
                {
                    var index = this.memory.StructureIdData.OtowerID.indexOf(ti)
                    this.memory.StructureIdData.OtowerID.splice(index,1)
                    continue
                }
                otlist.push(ot)
            }
        }
        

    }

    /* 爬虫信息手动调整 */
    public FinalSpawnData():void{
        if (!this.memory.spawnData) this.memory.spawnData = {}
        for (var role in this.memory.spawnData)
        {
            if (!global.CreepNumData[this.name][role]) delete this.memory.spawnData[role]
            global.CreepNumData[this.name][role].num = this.memory.spawnData[role]
        }
    }
}